import { ApolloClient } from 'apollo-client'
import { ApolloLink } from 'apollo-link'
import fetch from 'node-fetch'
import { createHttpLink  } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { onError } from 'apollo-link-error'
import { getAuthorization, setAuthorization } from '../utils/auth'

let apolloClient

export default {
  init () {
    const httpLink = createHttpLink({uri: 'http://127.0.0.1:7001/graphql', fetch: fetch})

    const middlewareLink = new ApolloLink ((operation, forward) => {
      operation.setContext({
        headers: {
          Authorization: getAuthorization()
        },
        credentials: "include"
      })
      // console.log(operation.getContext())
      return forward(operation).map((response) => {
        let authorization = operation.getContext().response.headers.get('Authorization')
        let authorizationExp = operation.getContext().response.headers.get('Authorization-Exp')
        if (authorization) {
          setAuthorization(authorization, authorizationExp)
        }
        return response
      })
    })

    const errorLink = onError(({networkError, graphQLErrors}) => {
      console.dir(networkError)
      console.log(graphQLErrors)
    })

    const link = middlewareLink.concat(errorLink).concat(httpLink);

    apolloClient = new ApolloClient({
      link: link,
      cache: new InMemoryCache(),
      connectToDevTools: false
    })
  },
  apollo () {
    return apolloClient
  }
}
